package com.small.os.minio.config;


import com.common.basis.exception.BusinessException;
import com.common.basis.result.Result;
import com.common.basis.result.ResultSet;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.io.IOException;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * mvc配置
 *
 * @author wangguochao
 */
@Slf4j
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        // 设置默认的加密方式
        return new BCryptPasswordEncoder();
    }

    /**
     * 统一异常处理
     */
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
        exceptionResolvers.add((request, response, handler, e) -> {
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            try {
                Result<?> error ;
                if (e instanceof InternalAuthenticationServiceException) {
                    error = ResultSet.error("用户名或密码错误");
                } else if (e instanceof InvalidGrantException) {
                    error = ResultSet.error("拒绝访问");
                } else if (e instanceof NoSuchElementException) {
                    error = ResultSet.error("未找到记录");
                } else if (e instanceof BusinessException) {
                    //自定义异常处理
                    error = ResultSet.error(e.getMessage());
                } else {
                    //500 内部错误
                    error = ResultSet.error("系统繁忙");
                    log.error(e.getMessage());//500
                }
                ObjectMapper objectMapper = new ObjectMapper();
                response.getWriter().write(objectMapper.writeValueAsString(error));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return new ModelAndView();
        });
    }
}
